package com.zq.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.zq.pojo.MsgInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service

public class ConsumerService {
    private  static final Logger logger= LoggerFactory.getLogger(ConsumerService.class);

    @Autowired
    private ObjectMapper objectMapper;





    @RabbitListener(queues = {"manualQueue"})
    public void consumer(Message message, Channel channel) throws IOException {
        MessageProperties messageProperties = message.getMessageProperties();
        long deliveryTag = messageProperties.getDeliveryTag();
        byte[] body = message.getBody();
        try {
            MsgInfo msgInfo = objectMapper.readValue(body, MsgInfo.class);
            logger.info("消费开始");
            Thread.sleep(10000);
            channel.basicAck(deliveryTag,true);
            logger.info("消费成功"+msgInfo);
        } catch (IOException | InterruptedException e) {

            channel.basicReject(deliveryTag,false);
            //channel.basicNack(deliveryTag,true,false);
            channel.basicPublish(messageProperties.getReceivedExchange(),messageProperties.getReceivedRoutingKey(),null,body);
        }
    }
}
